package com.miyu.common.utils.page;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.miyu.common.pojo.book.BookOperate;
import com.miyu.common.pojo.book.BookPage;
import com.miyu.common.utils.commonUtils.Comutils;
import org.apache.commons.lang3.StringUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Selectable;

import java.util.List;
import java.util.Map;

/**
 * 常见书jx
 * 解析数据面
 * @author miyu
 * @date 2022/07/12
 */
public class CommonBookJx {
    /**
     * 图书搜索
     * 搜索解析
     * @param page 页面
     * @throws Exception 异常
     */
    public static void BookSearch(Page page) throws Exception {
        //当前url连接
        String url = page.getRequest().getUrl();
        //参数
        BookPage pagePJ= page.getRequest().getExtra("param");
        //缓存key
        String key = pagePJ.getKey();
        //解析临时数据
        JSONObject temp = pagePJ.getTemp();
        //获取当前页搜索规则
        JSONObject bookSearch = pagePJ.getRule().getJSONObject(BookOperate.SEARCH.getCode());
        //固定值不可改变 bookList
        List<Selectable> list = JXPageUtils.JXPageRuleByPage(page,bookSearch.getString("bookList"));
        JSONObject showTitle = bookSearch.getJSONObject("showTitle");
        JSONArray ja = new JSONArray();
        for(int i=0;i<list.size();i++) {
            Selectable stable = list.get(i);
            JSONObject jo = new JSONObject();
            for (Map.Entry entry : showTitle.entrySet()) {
                String v = entry.getValue().toString();
                String k = entry.getKey().toString();
                if (v.trim().length() > 0) {
                    if (key.indexOf("#") > 0) {
                        //#做数据分割可做动态表头查询数据 以及取值数据扩展
                        String value = JXPageUtils.JXPageRuleByTable(stable, v);
                        if (StringUtils.isNotBlank(value)) {
                            jo.put(k.substring(0, k.indexOf("#")) , value);
                        }
                    } else {
                        String value = JXPageUtils.JXPageRuleByTable(stable, v);
                        if(StringUtils.isNotBlank(value)) {
                            jo.put(k , value);
                        }
                    }
                }
            }
            if(!jo.isEmpty()) {
                jo.put("ruleId",pagePJ.getRuleId());
                ja.add(jo);
            }
        }
        //解析完成移除当前解析规则
        page.putField("rule",pagePJ);
        page.putField("data",ja);
    }

    /**
     * 书籍详细信息
     * 本书章节列表
     * 明细解析
     * @param page 页面
     * @throws Exception 异常
     */
    public static void bookDetail(Page page) throws Exception {
        /**当前url连接*/
        String url = page.getRequest().getUrl();
        /**参数*/
        BookPage pagePJ= page.getRequest().getExtra("param");
        /**缓存key*/
        String key = pagePJ.getKey();
        //解析临时数据
        JSONObject temp = pagePJ.getTemp();
        /**明细规则*/
        JSONObject rule = pagePJ.getRule().getJSONObject(BookOperate.DETAIL.getCode());
        /**固定值不可改变 bookList*/
        Selectable selectable=null;
        if(StringUtils.isNotBlank(rule.getString("bookBox"))){
            selectable = JXPageUtils.JXPageRuleByPage(page,rule.getString("bookBox")).get(0);
        }else{
            /**当前页面*/
            selectable = page.getHtml().xpath("//body");
        }
        JSONObject detail = rule.getJSONObject("bookDetail");
        JSONObject btem = new JSONObject();
        for (Map.Entry entry : detail.entrySet()) {
            String v = entry.getValue().toString();
            if(v.trim().length()>0){
                btem.put(entry.getKey().toString(),JXPageUtils.JXPageRuleByTable(selectable,v));
            }
        }
        String bookId= Comutils.MD5(page.getUrl().toString());
        if(detail.containsKey("chapterUrl")&&detail.getString("chapterUrl").length()==0){
            btem.put("chapterUrl",page.getUrl().toString());
        }
        //来源规则
        btem.put("ruleId",pagePJ.getRuleId());
        //当前数据ID链接生成ID
        btem.put("fpk",bookId);
        //当前书籍链接
        btem.put("bookUrl",page.getUrl().toString());
        page.putField("rule",pagePJ);
        page.putField("data",btem);
    }

    /**
     * 章节解析
     * @param page
     * @throws Exception
     */
    public static void bookChapter(Page page) throws Exception {
        /**当前url连接*/
        String url = page.getRequest().getUrl();
        /**参数*/
        BookPage pagePJ= page.getRequest().getExtra("param");
        /**缓存key*/
        String key = pagePJ.getKey();
        //解析临时数据同用数据
        JSONObject temp = pagePJ.getTemp();
        /**明细规则*/
        //书籍章节取值 独立只取章节
        JSONObject  bookRule = pagePJ.getRule().getJSONObject(BookOperate.CHAPTER.getCode());
        String bc = bookRule.getString("bookChapterList");
;       JSONObject chapterList = new JSONObject();
        List<Selectable> chapterlist = JXPageUtils.JXPageRuleByPage(page,bc);
        JSONObject chapterInfo = bookRule.getJSONObject("bookChapterInfo");
        JSONArray cl = new JSONArray();
        for (int i=0;i<chapterlist.size();i++){
            Selectable stable = chapterlist.get(i);
            JSONObject jo = new JSONObject();
            for (Map.Entry entry : chapterInfo.entrySet()) {
                String v = entry.getValue().toString();
                if(v.trim().length()>0){
                    //加入规则Id
                    jo.put("ruleId",pagePJ.getRuleId());
                    //增加排序
                    jo.put("num",i+1);
                    jo.put("bookUrl",temp.getString("bookUrl"));
                    //判断是否是末级处理
                    if(i==0) {
                        jo.put("frist","1");
                    }
                    if(i==chapterlist.size()-1) {
                        jo.put("last","1");
                    }
                    jo.put(entry.getKey().toString(), JXPageUtils.JXPageRuleByTable(stable, v));
                }
            }
            cl.add(jo);
        }
        page.putField("rule",pagePJ);
        page.putField("data",cl);
    }

    /**
     * 图书阅读器
     * 阅读页面
     * @param page 页
     * @throws Exception 例外
     */
    public static void bookReader(Page page) throws Exception {
        /**当前url连接*/
        String url = page.getRequest().getUrl();

        /**参数*/
        BookPage pagePJ= page.getRequest().getExtra("param");
        /**缓存key*/
        String key = pagePJ.getKey();
        //解析临时数据
        JSONObject temp = pagePJ.getTemp();
        JSONObject cptRule = pagePJ.getRule().getJSONObject("bookReader");
        JSONObject params = pagePJ.getParam();
        Selectable selectable=null;
        if(StringUtils.isNotBlank(cptRule.getString("readBox"))){
            selectable = JXPageUtils.JXPageRuleByPage(page,cptRule.getString("readBox")).get(0);
        }else{
            /*当前页面*/
            selectable = page.getHtml().xpath("//body");
        }
        JSONObject bookReadBox = cptRule.getJSONObject("bookReadBox");
        temp.put("contextUrl",url);
        //加入规则Id
        if (params.containsKey("frist")){
            /*第一章*/
            temp.put("up","1");
            temp.put("frist","1");
        }else{
            temp.put("up","0");
        }
        if(params.containsKey("isLast")){
            /*最新章*/
            temp.put("next","1");
            temp.put("isLast","1");
        }else{
            temp.put("next","0");
        }
        /*赋值当前小说明细页*/
        if(params.containsKey("bookUrl")){
            temp.put("bookUrl",params.getString("bookUrl"));
        }else{
            temp.put("bookUrl","");
        }
        temp.put("ruleId",pagePJ.getRuleId());
        for (Map.Entry entry : bookReadBox.entrySet()) {
            String v = entry.getValue().toString();
            if(v.trim().length()>0){
                temp.put(entry.getKey().toString(), JXPageUtils.JXPageRuleByTable(selectable, v));
            }
        }
        page.putField("rule",pagePJ);
        page.putField("data",temp);
    }


    /**
     * 收集书籍
     * 书籍采集
     * @param page 页面
     * @throws Exception 例外
     */
    public static void collectBook (Page page)  throws Exception {
        /**详情 章节在同一页面*/
        /**获取规则参数*/
        BookPage pagePJ= page.getRequest().getExtra("param");
        /**当前缓存key*/
        String key = pagePJ.getKey();
        JSONObject temp = pagePJ.getTemp();
        if(temp.containsKey("bookDetail")){
            //已包含书籍详情
            System.out.println("已包含书籍详情");
            /**根据章节获取阅读内容*/
            page.putField("rule",pagePJ);
            page.putField("data",temp);

        }else{
            /**明细规则*/
            JSONObject bookDetail = pagePJ.getRule().getJSONObject("bookDetail");
            /**固定值不可改变 bookList*/
            Selectable selectable=null;
            if(StringUtils.isNotBlank(bookDetail.getString("bookBox"))){
                selectable = JXPageUtils.JXPageRuleByPage(page,bookDetail.getString("bookBox")).get(0);
            }else{
                /**当前页面*/
                selectable = page.getHtml().xpath("//body");
            }
            JSONObject bd = bookDetail.getJSONObject("bookDetail");
            JSONObject btem = new JSONObject();
            for (Map.Entry entry : bd.entrySet()) {
                String v = entry.getValue().toString();
                if(v.trim().length()>0){
                    btem.put(entry.getKey().toString(),JXPageUtils.JXPageRuleByTable(selectable,v));
                }
            }
            String bookId= Comutils.MD5(page.getUrl().toString());
            //来源规则
            btem.put("ruleId",pagePJ.getRuleId());
            //当前数据ID链接生成ID
            btem.put("fpk",bookId);

            //当前书籍链接
            btem.put("bookUrl",page.getUrl().toString());
            temp.put("bookDetail",btem);
            pagePJ.setTemp(temp);

            page.getRequest().putExtra("param",pagePJ);
            page.getRequest().setUrl(page.getUrl().toString());
            page.addTargetRequest(page.getRequest());
        }
    }

    /**
     * 检查规则
     * @param page 页
     * @throws Exception 例外
     */
    public static void checkRule(Page page)  throws Exception{
        /**当前缓存key*/
        String key = page.getRequest().getExtra("key");
        /**获取规则参数*/
        BookPage pagePJ= page.getRequest().getExtra("param");
        JSONObject temp = pagePJ.getTemp();
        temp.put("checkValue",JXPageUtils.JXPageRuleByCheckRule(page,pagePJ.getRuleStr()));

        page.putField("rule",pagePJ);
        page.putField("data",temp);
    }

    /**
     * 下载书籍
     * 原始章节下载书
     * @param page 页面
     */
    public static void downloadBook(Page page) {
    }
}
